<template>
	<view>
		<wd-message-box />
		<wd-toast />
		<!-- ✅ 年份选择器：仅在历史数据 tab 显示 -->
		<view class="px-4 py-2" v-if="activeTab === 'historyList'">
			<wd-datetime-picker type="year" v-model="yearTimestamp" label="按照年份搜索" :default-value="Date.now()" />
		</view>
		<wd-search v-model="searchValue" @search="handlesearch" hide-cancel placeholder-left placeholder="请输入关键字">
			<template #prefix>
				<wd-popover mode="menu" :content="menu" @menuclick="handleSearchChange">
					<view class="search-type">
						<text>{{ searchType }}</text>
						<wd-icon custom-class="icon-arrow" name="fill-arrow-down"></wd-icon>
					</view>
				</wd-popover>
			</template>
		</wd-search>



		<!-- <wd-table :data="list" :height="600" :border="false" @row-click="handleClick">
			<wd-table-col prop="title" label="标题" width="160px" align="center"></wd-table-col>
			<wd-table-col prop="grade" label="审批状态" align="center">
				<template #value="{ row }">
					<wd-tag custom-class="space" type="primary">
						{{ getDict(DICT_TYPE.BPM_TASK_STATUS, row.status) }}
					</wd-tag>
				</template>
			</wd-table-col>
			<wd-table-col prop="grade" label="操作" width="200" fixed align="left">
				<template #value="{ row }">
					<span class="px-1">
						<wd-button type="text" @click="handleProcessDetail(row)">
							查看
						</wd-button>
					</span>
					<span class="px-1">
						<wd-button type="text"
							@click="row.status === 3 || row.status === 4 ? handleAddOrEdit(row.id, true) : handleAddOrEdit(row.id)">
							{{ row.status === 0 ? '修改' : row.status === 4 || row.status === 3 ? '重新填写' : '' }}
						</wd-button>
					</span>
					<span class="px-1">
						<wd-button type="text" @click="handleDelete(row.id)">
							{{ row.status === 0 ? '取消' : '' }}
						</wd-button>
					</span>
				</template>
			</wd-table-col>
		</wd-table> -->
		<wd-tabs v-model="activeTab" auto-line-width @change="handleTabChange">
			<wd-tab v-for="tab in tabs" :key="tab.value" :title="tab.label" :name="tab.value">
				<view class="px-1 py-1">
					<wd-table :data="list[tab.value]" :height="600" :border="false" @row-click="handleClick">
						<wd-table-col v-for="(col, index) in columns[tab.value]" :key="index" :prop="col.prop"
							:label="col.label" :width="col.width || '100'" :align="col.align || 'center'">
							<template #value="{ row }">
								<template v-if="col.prop.includes('.')">
									<!-- 如果是嵌套属性，拆分路径并按路径访问数据 -->
									{{ getNestedValue(row, col.prop) || '-' }}
								</template>
								<template v-else-if="col.isTag">
									<wd-tag custom-class="space"
										:type="col.color ? col.color(row[col.prop]) : 'primary'">
										{{ col.format ? (col.format(row[col.prop]) || '-') : (row[col.prop] || '-') }}
									</wd-tag>
								</template>
								<template v-else>
									{{ col.format ? (col.format(row[col.prop]) || '-') : (row[col.prop] || '-') }}
								</template>
							</template>
						</wd-table-col>
						<wd-table-col prop="grade" label="操作" width="200" fixed align="center">
							<template #value="{ row }">
								<text class="px-1 text-#4d80f0" @click.stop="handleProcessDetail(row)">
									查看
								</text>
								<text class="px-1 text-#4d80f0" v-if="row.status === 3"
									@click.stop="row.status === 3  ? handleAddOrEdit(row.id, true) : handleAddOrEdit(row.id)">
									{{ row.status === 0 ? '修改' :  row.status === 3 ? '重新填写' : ''
									}}
								</text>
								<text class="px-1 text-#4d80f0" @click.stop="handleDelete(row.id)">
									{{ row.status === 0 ? '取消' : '' }}
								</text>
								<text class="px-1 text-#4d80f0" @click.stop="handleExpedite(row)">
									{{ row.status !== 2 && row.status !== 4 ? '催办' : '' }}
								</text>
							</template>
						</wd-table-col>
					</wd-table>
				</view>
			</wd-tab>
		</wd-tabs>
		<!-- 分页组件 -->
		<Pagination :total="total" :pageNo="queryParams.pageNo" :pageSize="queryParams.pageSize"
			@update:pageNo="changePage" />
		<view class="mx-12 my-8 ">
			<up-button text="新增" color="#5ac725" shape="circle" @click="handleAddOrEdit()"
				v-if="activeTab === `currentList`"></up-button>
		</view>


	</view>
</template>

<script setup lang="ts">
import { onShow } from '@dcloudio/uni-app'
import { ref, onMounted, nextTick, watch } from 'vue'
import { postManagementVO } from '@/api/oa/postManagement'
import * as postManagementApi from '@/api/oa/postManagement'
import { DICT_TYPE, getIntDictOptions, getDictLabel, getDictColor } from '@/utils/dict'
import Pagination from '@/components/pagination/index.vue'
import { useMessage, useToast } from 'wot-design-uni'
import { expediting } from '@/utils/processinstance'
import dayjs from 'dayjs'

const message = useMessage()
const toast = useToast()

/**日期选择器默认值 */
const yearTimestamp = ref<number>(Date.now())
//存储数据
const list = ref<any>({
	currentList: [],  // 集团起诉案件审批
	historyList: [],   // 集团应诉案件审批
})
// 表单列配置项
const columns = {
	currentList: [
		{ prop: 'title', label: '标题', width: 160 },
		{
			prop: 'status',
			label: '审批状态',
			align: 'center',
			width: 110,
			format: (val: any) => getDictLabel(DICT_TYPE.BPM_TASK_STATUS, val),
			color: (val: any) => getDictColor(DICT_TYPE.BPM_TASK_STATUS, val),
			isTag: true
		}

	],
	historyList: [
		{ prop: 'title', label: '标题', width: 160 },
		{
			prop: 'status',
			label: '审批状态',
			align: 'center',
			width: 110,
			format: (val: any) => getDictLabel(DICT_TYPE.BPM_TASK_STATUS, val),
			color: (val: any) => getDictColor(DICT_TYPE.BPM_TASK_STATUS, val),
			isTag: true
		}

	]

} as any
const activeTab = ref('currentList')
const tabs = ref([
	{
		label: '发文审批',
		value: 'currentList',
		api: postManagementApi.getOutGoingPage,
	},
	{
		label: '历史数据',
		value: 'historyList',
		api: postManagementApi.getOutGoingHistoryByYear,
	}
])
// 响应式数据
// const list = ref<postManagementVO[]>([])
const queryParams = ref<any>({
	pageNo: 1,
	pageSize: 10,
	title: undefined,
	type: undefined,
	// year: dayjs().year()
	// year: new Date(yearTimestamp.value).getFullYear()
	year: dayjs(yearTimestamp.value).year()
})
const total = ref(0)
const loading = ref(false)

const searchType = ref<string>('发文标题')
const searchValue = ref<string>('')
const menu = ref<any[]>([
	{
		content: '发文标题',
		prop: 'title'
	},
])
/** 监听年份选择器的值变化 */
watch(yearTimestamp, (val) => {
	// 转换时间戳为年份字符串
	queryParams.value.year = dayjs(val).year();
	fetchList(); // 选中年份后直接刷新数据
});


const handleTabChange = async (value: any) => {
	searchValue.value = ''
	queryParams.value.title = undefined;
	queryParams.value.title = undefined;
	await nextTick();
	fetchList();

}
function handleSearchChange({ item }: { item: any }) {
	searchType.value = item?.content
}
const handlesearch = () => {
	// 找到选中的搜索字段
	const selectedMenu = menu.value.find(item => item.content === searchType.value);
	if (selectedMenu) {
		// 清空之前的搜索条件
		queryParams.value.title = undefined;
		// queryParams.value.title = undefined;
		// 根据选中的搜索类型设置搜索值
		if (activeTab.value === 'currentList') {
			queryParams.value.title = searchValue.value.trim()
		} else {
			queryParams.value.title = searchValue.value.trim()
		}
		// queryParams.value[selectedMenu.prop] = value.value.trim();
		// 重新获取数据
		fetchList();
	}
};

// 切换分页
const changePage = (newPage: any) => {
	queryParams.value.pageNo = newPage
	fetchList()
}
// 获取单个 tab 数据
const fetchList = async () => {
	const currentTab = tabs.value.find(t => t.value === activeTab.value);
	if (!currentTab) return;

	loading.value = true;
	try {
		const response = await currentTab.api(queryParams.value);
		list.value[activeTab.value] = response.list
		console.log('list.value', list.value);
		total.value = response.total;
		for (let item of list.value[activeTab.value]) {
			item.status = item.isApproved === false ? 0 : item.status;
		}
		console.log('list.value', list.value);
	} catch (error) {
		console.error(error);
	} finally {
		loading.value = false;
	}
};
// /** 审批进度 */
// const handleProcessDetail = (row: any) => {
// 	const url = `/pagesPackage/OAsystemAutomation/outgoingDocument/detail?processInstanceId=${row.processInstanceId}&id=${row.id}`;
// 	uni.navigateTo({
// 		url: url
// 	});
// }
/** 查看详情页面 */
const handleProcessDetail = (row: any) => {
	let url = ''
	switch (activeTab.value) {
		case 'currentList':
			url = `/pagesPackage/OAsystemAutomation/outgoingDocument/detail?processInstanceId=${row.processInstanceId}&id=${row.id}`
			break
		case 'historyList':
			url = `/pagesPackage/OAsystemAutomation/outgoingDocument/detail?processInstanceId=${row.processInstanceId}&id=${row.id}`
			break
	}

	uni.navigateTo({ url })
}
/** 点击一整行跳转至详情页面 */
const handleClick = ({ rowIndex }: any, event: Event) => {
	handleProcessDetail(list.value[activeTab.value][rowIndex])

}

/** 新增或编辑页面 */
const handleAddOrEdit = (id?: any, resubmit = false) => {
	let url = ''
	switch (activeTab.value) {
		case 'currentList':
			url = `/pagesPackage/OAsystemAutomation/outgoingDocument/createOrUpdate`
			break
		case 'historyList':
			url = `/pagesPackage/OAsystemAutomation/outgoingDocument/createOrUpdate`
			break
	}

	if (id) {
		if (resubmit === true) {
			console.log('resubmit', resubmit);
			url += `?id=${id}&resubmit=1`;
		}
		console.log('传过来的Id', id);
		url += `?id=${id}&resubmit=0`;
	} else {
		url += `?resubmit=0`;
	}

	uni.navigateTo({ url })
}

/** 删除操作 */
const handleDelete = async (id: number) => {
	try {
		await message.confirm({
			msg: '您确定要取消吗？',
			title: '提示',
		})

		const apiMap: Record<string, Function> = {
			lawsuitapproval: postManagementApi.deleteOutGoing,
			lawsuitdefense: postManagementApi.deleteOutGoing,

		}

		const api = apiMap[activeTab.value]
		if (!api) throw new Error('未找到对应 API')

		await api(id)
		toast.success('取消成功')
		await fetchList()
	} catch (error) {
		console.log('用户取消了操作或发生错误:', error)
	}
}
/**催办 */
const handleExpedite = (row: any) => {
	expediting({
		processInstanceId: row.processInstanceId,
		processName: '青运-办公系统自动化-发文审核'
	})
}
// /** 新增页面 */
// const handleAddOrEdit = (id?: any, resubmit = false) => {
// 	let url = `/pagesPackage/OAsystemAutomation/outgoingDocument/createOrUpdate`; // 默认新增页面
// 	// 如果 id 存在，拼接 id 作为参数
// 	if (id) {
// 		if (resubmit === true) {
// 			console.log('resubmit', resubmit);
// 			url += `?id=${id}&resubmit=1`;
// 		}
// 		console.log('传过来的Id', id);
// 		url += `?id=${id}&resubmit=0`;
// 	} else {
// 		url += `?resubmit=0`;
// 	}
// 	uni.navigateTo({ url });
// }
// /** 删除按钮操作 */
// const handleDelete = async (id: number) => {
// 	try {
// 		// 删除的二次确认
// 		await message.confirm({
// 			msg: '您确定要取消吗？',
// 			title: '提示'  // 添加标题
// 		})
// 		// 发起删除
// 		await postManagementApi.deleteOutGoing(id)
// 		// 显示成功提示
// 		toast.success('取消成功')
// 		// 刷新列表
// 		await fetchList()
// 	} catch (error) {
// 		console.log('用户取消了操作或发生错误:', error)
// 	}
// }
// 生命周期
onMounted(() => {
	fetchList()
})
onShow(() => {
	fetchList()
})
</script>

<style scoped lang="scss">
.container {
	padding: 20px 10px;
}

.search-type {
	position: relative;
	height: 30px;
	line-height: 30px;
	padding: 0 8px 0 16px;
}

.search-type::after {
	position: absolute;
	content: '';
	width: 1px;
	right: 0;
	top: 5px;
	bottom: 5px;
	background: rgba(0, 0, 0, 0.25);
}

.search-type {
	:deep(.icon-arrow) {
		display: inline-block;
		font-size: 20px;
		vertical-align: middle;
	}
}
</style>